package com.wei.czz.framework.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wei.czz.common.enums.CommonEnum;
import com.wei.czz.common.enums.ResultEnum;
import com.wei.czz.common.dto.admin.userRisk.UserRiskDto;
import com.wei.czz.common.exception.CzzException;
import com.wei.czz.common.tool.PageDto;
import com.wei.czz.common.tool.PageQuery;
import com.wei.czz.common.utils.TimeUtils;
import com.wei.czz.common.vo.admin.userRisk.UserRiskFormVo;
import com.wei.czz.framework.admin.dao.UserRiskFlowDao;
import com.wei.czz.framework.admin.entity.UserRiskFlowEntity;
import com.wei.czz.framework.admin.service.UserRiskFlowService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.*;

/**
 * Created by IntelliJ IDEA.
 *
 * @author wei
 * date: 2022-04-15 21:40:39
 * className: UserRiskFlowServiceImpl 用户风险记录请求服务接口实现类
 * version: 1.0
 * description:
 */
@Service("userRiskFlowService")
public class UserRiskFlowServiceImpl extends ServiceImpl<UserRiskFlowDao, UserRiskFlowEntity> implements UserRiskFlowService {

    private static final Logger log = LoggerFactory.getLogger(UserRiskFlowServiceImpl.class);

    @Override
    public void saveOrEdit(UserRiskFlowEntity userRiskFlow) {
        Long id = userRiskFlow.getId();
        if (Objects.isNull(id)) {

            int count = baseMapper.insert(userRiskFlow);
            log.info("插入用户风控记录完成。count={}", count);
        } else {

            int count = baseMapper.updateById(userRiskFlow);
            log.info("修改用户风控记录完成。count={}", count);
        }
    }

    @Override
    public PageDto<UserRiskFlowEntity> getPageList(UserRiskFormVo userRiskFormVo) {

        if (Objects.nonNull(userRiskFormVo.getEndCreateTime())) {
            // 数据格式化
            userRiskFormVo.setEndCreateTime(TimeUtils.getEndDate(userRiskFormVo.getEndCreateTime()));
        }

        // 创建mp分页对象
        Page<UserRiskFlowEntity> page = PageQuery.initPage(userRiskFormVo);

        LambdaQueryWrapper<UserRiskFlowEntity> userRiskFlowLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 匹配 用户主键、风控类型、风控状态、创建时间（范围） 字段
        userRiskFlowLambdaQueryWrapper.eq(Objects.nonNull(userRiskFormVo.getUserId()), UserRiskFlowEntity::getUserId,
                        userRiskFormVo.getUserId())
                .eq(Objects.nonNull(userRiskFormVo.getRiskType()), UserRiskFlowEntity::getRiskType,
                        userRiskFormVo.getRiskType())
                .eq(Objects.nonNull(userRiskFormVo.getStatus()), UserRiskFlowEntity::getStatus,
                        userRiskFormVo.getStatus())
                .ge(Objects.nonNull(userRiskFormVo.getStartCreateTime()), UserRiskFlowEntity::getCreateTime,
                        userRiskFormVo.getStartCreateTime())
                .le(Objects.nonNull(userRiskFormVo.getEndCreateTime()), UserRiskFlowEntity::getCreateTime,
                        userRiskFormVo.getEndCreateTime());

        // 查询数据库用户风险记录表
        this.page(page, userRiskFlowLambdaQueryWrapper);
        log.info("分页查询用户风控记录完成。list.size={} totalNum={}", page.getRecords().size(), page.getTotal());

        // 封装返回
        return new PageDto<>(page);
    }

    @Override
    public UserRiskFlowEntity get(Long id) {
        UserRiskFlowEntity userRiskFlow = baseMapper.selectById(id);
        if (Objects.isNull(userRiskFlow)) {
            log.info("用户风控记录不存在");
            throw new CzzException(ResultEnum.REQUEST_FAIL.getCode(), "用户风控记录不存在，请确认");
        }
        if (CommonEnum.ONE.getValue().equals(userRiskFlow.getDeleteStatus())) {
            log.info("用户风控记录已删除");
            throw new CzzException(ResultEnum.REQUEST_FAIL.getCode(), "用户风控记录不存在，请确认");
        }
        return userRiskFlow;
    }

    @Override
    public UserRiskDto getMyRisk(Long riskRecordId) {
        UserRiskFlowEntity userRisk;

        LambdaQueryWrapper<UserRiskFlowEntity> userRiskFlowLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 查询 风控类型和风控原因 字段
        userRiskFlowLambdaQueryWrapper.select(UserRiskFlowEntity::getRiskType, UserRiskFlowEntity::getRiskReason);
        // 匹配 风控主键 字段
        userRiskFlowLambdaQueryWrapper.eq(UserRiskFlowEntity::getId, riskRecordId);
        // 查询数据库用户风险表，获取用户风控信息
        List<UserRiskFlowEntity> userRiskList = this.list(userRiskFlowLambdaQueryWrapper);
        log.info("用户风控记录查询结果：size={}", userRiskList.size());
        if (userRiskList.isEmpty()) {
            userRisk = new UserRiskFlowEntity();
        } else {
            userRisk = userRiskList.get(0);
        }
        UserRiskDto userRiskDto = new UserRiskDto();
        userRiskDto.setRiskType(userRisk.getRiskType())
                .setRiskReason(userRisk.getRiskReason());
        return userRiskDto;
    }

    @Override
    public UserRiskFlowEntity findLastUserRiskFlow(Long userId) {
        LambdaQueryWrapper<UserRiskFlowEntity> userRiskLambdaWrapper = new LambdaQueryWrapper<>();
        // 匹配 用户id 字段
        userRiskLambdaWrapper.eq(UserRiskFlowEntity::getUserId, userId);
        // 根据 主键 倒叙排序
        userRiskLambdaWrapper.orderByDesc(UserRiskFlowEntity::getId);
        // 只获取一条信息
        userRiskLambdaWrapper.last("limit 1");
        // 查询数据库用户风险表，获取用户风控信息列表
        List<UserRiskFlowEntity> userRiskFlowList = this.list(userRiskLambdaWrapper);
        log.info("获取用户最新一条风控记录结果。size={}", userRiskFlowList.size());
        return Optional.of(userRiskFlowList)
                .filter(list -> !list.isEmpty())
                .map(list -> list.get(0))
                .orElse(null);
    }

    @Override
    public List<UserRiskFlowEntity> findUserRiskFlowList(Long userId) {
        LambdaQueryWrapper<UserRiskFlowEntity> userRiskFlowLambdaWrapper = new LambdaQueryWrapper<>();
        userRiskFlowLambdaWrapper.eq(UserRiskFlowEntity::getUserId, userId)
                .eq(UserRiskFlowEntity::getDeleteStatus, CommonEnum.ZERO.getValue());
        List<UserRiskFlowEntity> userRiskFlowList = baseMapper.selectList(userRiskFlowLambdaWrapper);
        log.info("查询用户风控记录完成。userId={} list.size={}", userId, userRiskFlowList.size());
        return userRiskFlowList;
    }

    @Override
    public Set<Long> getRiskUserIdSet() {
        Set<Long> userIdSet = baseMapper.getUserIdSet();
        log.info("查询被风控过的用户主键完成。set.size={}", userIdSet.size());
        return userIdSet;
    }

}